package com.mall.user.mq.delay;

import com.alibaba.fastjson.JSON;
import com.mall.user.config.EmailConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

@Slf4j
@Component
public class RegisterSendEmailProducer {
    private DefaultMQProducer producer;

    @Autowired
    private EmailConfig emailConfig;

    @PostConstruct
    public void init(){
        producer = new DefaultMQProducer("register_send_email_producer");
        producer.setNamesrvAddr("127.0.0.1:9876");
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public boolean sendRegisterEmailMessage(SimpleMailMessage simpleMailMessage){
        log.info("enter sendDelayOrderMessage {}", simpleMailMessage.getText());
        String data = JSON.toJSONString(simpleMailMessage);
        Message message = new Message();
        message.setTopic("register_send_email");
        message.setBody(data.getBytes(Charset.forName("utf-8")));
        SendResult send = null;
        try {
            log.info(" before send message", simpleMailMessage.getText());
            send = producer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (send != null && SendStatus.SEND_OK.equals(send.getSendStatus())){
            return true;
        }
        return false;
    }
}
